package com.pubinfo.passbook.common.service.master.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.entity.TRabbitmqPerson;
import com.pubinfo.passbook.common.entity.TSystemRole;
import com.pubinfo.passbook.common.mapper.TRabbitmqOrgConvertMapper;
import com.pubinfo.passbook.common.mapper.TRuleDistrictMapper;
import com.pubinfo.passbook.common.mapper.TSubsidiaryInfoMapper;
import com.pubinfo.passbook.common.mapper.TSystemRoleMapper;
import com.pubinfo.passbook.common.model.bo.witeoff.CityInfo;
import com.pubinfo.passbook.common.model.dto.role.RoleEditDTO;
import com.pubinfo.passbook.common.model.dto.system.RoleMenuParam;
import com.pubinfo.passbook.common.model.dubbo.ESBServiceData;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.manage.RolePermissionVo;
import com.pubinfo.passbook.common.service.dubbo.DubboService;
import com.pubinfo.passbook.common.service.master.TRabbitmqPersonService;
import com.pubinfo.passbook.common.service.master.TSystemRoleService;
import com.pubinfo.passbook.common.service.mss.HttpService;
import com.pubinfo.passbook.common.utils.task.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class TSystemRoleServiceImpl extends ServiceImpl<TSystemRoleMapper, TSystemRole>
    implements TSystemRoleService {
  @Autowired
  TRabbitmqPersonService personService;
  @Autowired
  TRabbitmqPersonService convertService;
  @Autowired
  TRuleDistrictMapper districtMapper;
  @Autowired
  DubboService dubboService;
  @Autowired
  TSubsidiaryInfoMapper infoMapper;
  
  @Resource
  TRabbitmqOrgConvertMapper convertMapper;
  @Autowired
  HttpService httpService;
  
  @Override
  public boolean addUserRole(Integer acctId, Integer roleId, Integer orgId) {
    //先删除之前的绑定关系
    delUserRole(roleId, acctId);
    TRabbitmqPerson person = personService.selectByAcctId(String.valueOf(acctId));
    return this.baseMapper.addUserRole(acctId, roleId, person.getAcct(), orgId);
  
  }
  
  @Override
  public String findAcctByAcct(String acct) {
    //如果是省公司，可能有多个部门报账员，通过报账员用户确定部门报账员
    //如果是温州地区，则查询角色用户关联表，获取审核员
//    if (personService.isShengGongSiPerson(acct)) {
//      return this.baseMapper.shengGongSiClerkByAcct(acct);
//    } else if (personService.isWenZhouPerson(acct)) {
//      ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
//      return this.baseMapper.findWenZhouPersonBySubName(certDetail.getSubsidiaryName());
//    }
  
    return this.baseMapper.findAuditUserByAcct(acct);
  }
  
  @Override
  public boolean delUserRole(Integer roleId, Integer acctId) {
    return this.baseMapper.delUserRole(roleId, acctId);
  }
  
  @Override
  public boolean addRoleMenu(Integer roleId, List<Integer> menuIdList) {
    menuIdList.removeIf(Objects::isNull);
    if (menuIdList.isEmpty()) return true;
    delRoleMenu(roleId);
    List<RoleMenuParam> roleMenuParamList = new LinkedList<>();
    for (Integer id : menuIdList) {
      RoleMenuParam roleMenuParam = new RoleMenuParam();
      roleMenuParam.setMenuId(id);
      roleMenuParam.setRoleId(roleId);
      roleMenuParamList.add(roleMenuParam);
    }
    return this.baseMapper.addPermRole(roleMenuParamList);
  }
  
  @Override
  public boolean delRoleMenu(Integer roleId) {
    return this.baseMapper.delPermRole(roleId, null);
  }
  
  @Override
  public String userNsrsbhByAcct(String acct) {
    ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
    if (certDetail != null) {
      String areaName = certDetail.getSubsidiaryName();
      CityInfo info = infoMapper.findCityInfoByNsrsbh(areaName);
      if (info != null) {
        return info.getNsrsbh();
      }
    }
    return null;
  }
  
  @Override
  public List<TSystemRole> listCurrentUserRole(String currentAcct) {
//    List<TSubsidiaryInfo> tSubsidiaryInfos = new LambdaQueryChainWrapper<TSubsidiaryInfo>(infoMapper).eq(TSubsidiaryInfo::getAuditUser, currentAcct).list();
//    /**
//     * 先查询用户是否为医药费审核员，如果不是，则查询角色表，关联后返回用户角色信息
//     * 如果是，则直接返回医药费审核员相关信息
//     */
//    List<TSystemRole> roleList = new ArrayList<>();
//    if (CollectionUtils.isEmpty(tSubsidiaryInfos)) {
//      String nsrsbh = userNsrsbhByAcct(currentAcct);
//      roleList = this.baseMapper.listRoleByAcct(currentAcct);
//
//      //查询账号拥有的部门报账员
//      List<TRabbitmqOrgConvert> converts = new LambdaQueryChainWrapper<TRabbitmqOrgConvert>(convertMapper).eq(TRabbitmqOrgConvert::getAuditUser, currentAcct).list();
//      if (!CollectionUtils.isEmpty(converts)) {
//        //根据部门查询公司组织代码
//        List<SubsidiaryDepartment> subsidiaryDepartmentList = infoMapper.listByAcctUser(currentAcct);
//        roleList = subsidiaryDepartmentList.stream().map(subsidiaryDepartment -> {
//          TSystemRole role = new TSystemRole(subsidiaryDepartment);
//          return role;
//        }).collect(Collectors.toList());
//      }
//      if (CollectionUtils.isEmpty(roleList)) {
//        roleList = new LambdaQueryChainWrapper<TSystemRole>(this.baseMapper).eq(TSystemRole::getRoleCode, "passbook_user").list();
//      }
//      roleList.forEach(role -> {
//        role.setNsrsbh(nsrsbh);
//      });
//    } else {
//      roleList = TSystemRole.toList(tSubsidiaryInfos);
//    }
//    roleList.forEach(role -> {
//      List<TSystemRole> roles = new LambdaQueryChainWrapper<TSystemRole>(this.baseMapper).eq(TSystemRole::getRoleCode, role.getRoleCode()).list();
//      role.setId(roles.get(0).getId());
//    });
    return null;
  }
  
  @Override
  public JsonResult<String> addRole(RoleEditDTO dto) {
    
    String roleName = "";
    CityInfo cityInfo = districtMapper.findCityInfoByDistrictId(dto.getDistrictId(), dto.getNsrsbh());
    List<String> nsrsbhs = ConstantUtil.getShengGongSiNsrsbh();
    if ("passbook_bill_auditor".equals(dto.getRoleCode())) {
      if (nsrsbhs.contains(cityInfo.getNsrsbh())) {
        //能找到，说明为省公司
        roleName = cityInfo.getSubName() + "-医药费审核员";
      } else {
        roleName = cityInfo.getCityName() + "-" + cityInfo.getDistrictName() + "-医药费审核员";
      }
    } else if ("passbook_reimbursement_clerk".equals(dto.getRoleCode())) {
      if (StringUtils.isBlank(dto.getDepartmentName())) {
        throw new IllegalArgumentException("如果是省公司并且角色类型为部门报账员，需要查询省公司列表接口，传送部门名称");
      }
      roleName = "省公司-" + dto.getDepartmentName() + "-部门报销员";
    }
    dto.setRoleName(roleName);
    TSystemRole role = new TSystemRole(dto);
    if (this.baseMapper.selectRoleByRoleName(role.getRoleName()) == null) {
      this.baseMapper.insert(role);
      if (addRoleMenu(role.getId(), dto.getMenuIds())) {
        return JsonResult.success("添加成功");
      }
    }
    return JsonResult.error("该角色已存在！");
  }
  
  @Override
  public boolean delRole(Integer roleId) {
    if (this.baseMapper.deleteById(roleId) > 0) {
      //删除角色和菜单对应关系
      delRoleMenu(roleId);
      //删除角色和用户对应关系
      delUserRole(roleId, null);
      return true;
    }
    return false;
  }
  
  @Override
  public List<RolePermissionVo> getRolePermission(Integer roleId) {
    return this.baseMapper.selectPermByroleId(roleId);
  }
  
  @Override
  public Boolean switchRole(String roleId, String acctId) {
    //先判断角色是否存在， 如果不存在，则返回false
    TSystemRole systemRole = getById(roleId);
    if (systemRole != null) {
      return this.baseMapper.updateUserRoleByAcctId(acctId, roleId);
    }
    return false;
  }
  
  @Override
  public String selectRoleByAcct(String acct) {
    TSystemRole role = this.baseMapper.selectRoleByAcct(acct);
    return role.getRoleCode();
  }
  
  @Override
  public String selectRoleNameByAcct(String acct) {
    TSystemRole role = this.baseMapper.selectRoleByAcct(acct);
    return role != null ? role.getRoleName() : null;
  }
  
  /**
   * 根据用户ID获得对应角色的所有权限,如果没有对应角色那就默认使用普通用户角色
   *
   * @param acctId
   * @return
   */
  @Override
  public List<RolePermissionVo> getPersonMenu(Integer acctId) {
    List<RolePermissionVo> result = this.baseMapper.selectPersonMenu(acctId);
    
    /**
     * 如果菜单权限为空,就默认使用普通用户
     */
    if (result.isEmpty()) {
      TSystemRole role = new LambdaQueryChainWrapper<>(baseMapper)
          .eq(TSystemRole::getRoleCode, "passbook_user")
          .one();
      return getRolePermission(role.getId());
    }
    
    return result;
  }
  
}
